import React, { Component } from 'react';
import {
    AppRegistry,
    StyleSheet,
    Text,
    View,
    Image,
    Navigator,
    WebView,TextInput,DeviceEventEmitter
} from 'react-native';
import NavigationBar from '../common/NavigationBar'
import ViewUtils from '../util/ViewUtils'

const URL = 'https://www.baidu.com';
const TRENDING_URL = 'https://github.com/'
export default class RepositoryDetail extends Component {
    constructor(props) {
        super(props)
        this.url = this.props.item.html_url ? this.props.item.html_url : TRENDING_URL + this.props.item.fullName
        this.title = this.props.item.full_name ? this.props.item.full_name : this.props.item.fullName
        this.state={
            url: URL,
            title: this.title,
            canGoBack: false
        }
    }
    onBack() {
        if(this.state.canGoBack) {
            this.webView.goBack()
            this.text=this.state
        } else {
            this.props.navigator.pop()
            DeviceEventEmitter.emit('showToast', '无上一页，返回首页')
        }
    }
    goTo() {
        this.setState({
            url: this.text
        })
    }
    onNavigationStateChange(e) {
        this.setState({
            canGoBack: e.canGoBack,
            url: e.url
        })
    }
    render() {
        return (
            <View style={styles.container}>
                <NavigationBar
                    title={this.state.title}
                    leftButton={ViewUtils.getLeftButton(() => {this.onBack()})}
                />
                <View style={styles.row}>
                    <Text style={styles.tips} onPress={()=>this.goBack()}>返回</Text>
                    <TextInput style={styles.input} defaultValue={this.url} onChangeText={text=>this.text=text}/>
                    <Text style={styles.tips} onPress={()=>this.goTo()}>前往</Text>
                </View>
                <WebView
                    ref={webView=>this.webView=webView}
                    source={{uri: this.state.url}}
                    onNavigationStateChange={e=>this.onNavigationStateChange(e)}
                    startInLoadingState={true}/>
            </View>
        )
    }
}

const styles = StyleSheet.create({
    container: {
        flex: 1,
        backgroundColor: 'red',
        justifyContent: 'center'
    },
    text: {
        fontSize: 20
    },
    tips: {
        fontSize: 20
    },
    row: {
        flexDirection: 'row',
        alignItems: 'center',
        margin: 10
    },
    input: {
        height: 40,
        flex: 1,
        borderWidth: 1,
        margin: 2
    }
});